package com.ysxsoft.wdg.ui.activity.my;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.classic.common.MultipleStatusView;
import com.google.gson.Gson;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.UserInfoBean;
import com.ysxsoft.wdg.bean.response.DaiLiShenQingResponse;
import com.ysxsoft.wdg.bean.response.DlLevelBean;
import com.ysxsoft.wdg.bean.response.GetCodeResponse;
import com.ysxsoft.wdg.bean.response.ShopCateResponse;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.ui.activity.my.ShopRzInputActivity;
import com.ysxsoft.wdg.ui.activity.my.qydl.QuDlInputActivity;
import com.ysxsoft.wdg.ui.activity.order.AplyBackOrderActivity;
import com.ysxsoft.wdg.util.Base64Utils;
import com.ysxsoft.wdg.util.ImageUtils;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.camera.CameraUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.util.statusbar.StatusBarUtil;
import com.ysxsoft.wdg.widget.alertview.AlertUtils;
import com.ysxsoft.wdg.widget.alertview.AlertViewFactory;
import com.ysxsoft.wdg.widget.alertview.OnItemClickListener;
import com.ysxsoft.wdg.widget.city.JsonBean;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.Call;

public class ShopRzInputActivity extends BaseActivity implements BGASortableNinePhotoLayout.Delegate {


    public static void start(Context context) {
        Intent intent = new Intent(context, ShopRzInputActivity.class);
        context.startActivity(intent);
    }

    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_finish)
    ImageView titleFinish;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.tv_rz_type)
    TextView tvRzType;
    @BindView(R.id.et_shop_name)
    EditText etShopName;
    @BindView(R.id.tv_shop_type)
    TextView tvShopType;
    @BindView(R.id.et_name)
    EditText etName; @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;
    @BindView(R.id.yqm)
    EditText yqm;
    @BindView(R.id.et_id)
    EditText etId;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.et_address_detail)
    EditText etAddressDetail;
    @BindView(R.id.iv_id_z)
    ImageView ivIdZ;
    @BindView(R.id.iv_id_f)
    ImageView ivIdF;
    @BindView(R.id.btn_sure)
    TextView btnSure;
    @BindView(R.id.ninePhotoLayout)
    BGASortableNinePhotoLayout mPhotosSnpl;
    private String province, city;
    private String leftImagePath, rightImagePath;
    private String pic;
    private boolean isShopSelected = false;
    //选择器
    private OptionsPickerView pvOptions;
    private List<String> strList = new ArrayList<>();
    private List<ShopCateResponse.DataBean> levelList = new ArrayList<>();
    //地址选择器
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private String uid, levelid, realName, shenfenNo, tele, county, money;
    private boolean isLoaded;
    private boolean isLeftClicked;
    private String leftid, rightid, zzid;//图片上传id
    private static final int PRC_PHOTO_PICKER = 1;
    private static final int RC_CHOOSE_PHOTO = 1;
    private static final int RC_PHOTO_PREVIEW = 2;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shop_rz_input;
    }

    @Override
    protected void initData() {
        StatusBarUtil.setStatusBarTextColor(this, true);
        initStatusBar(topView, true);
        titleContent.setText("填写信息");
        //解析城市数据
        mHandler.sendEmptyMessage(MSG_LOAD_DATA);

        initSnpl();
        getLevels();//获取店铺类型
        getCode();
    }

    @Override
    protected void setListener() {

    }

    /**
     * 初始化九宫格图片控件
     */
    private void initSnpl() {
        //设置最大选择张数
        mPhotosSnpl.setMaxItemCount(9);
        //设置是否可编辑
        mPhotosSnpl.setEditable(true);
        //显示九图控件的加号按钮
        mPhotosSnpl.setPlusEnable(true);
        //是否可拖拽排序
        mPhotosSnpl.setSortable(true);
        //设置拖拽排序控件的代理
        mPhotosSnpl.setDelegate(this);
    }


    @OnClick({R.id.title_finish, R.id.tv_rz_type, R.id.tv_shop_type,
            R.id.tv_address, R.id.iv_id_z, R.id.iv_id_f, R.id.btn_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                finish();
                break;
            case R.id.tv_rz_type:
                break;
            case R.id.tv_shop_type:
                setPickerView();
                break;
            case R.id.tv_address:
                selectAddress();
                break;
            case R.id.iv_id_z:
                isLeftClicked = true;
                isShopSelected = false;
                AlertViewFactory.getInstance().getPhotoTypeAlertView(this, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            new RxPermissions(ShopRzInputActivity.this)
                                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) {
                                            CameraUtils.getInstance().takeCamera(ShopRzInputActivity.this);
                                        }
                                    });
                        } else if (position == 1) {
                            new RxPermissions(ShopRzInputActivity.this)
                                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) {
                                            CameraUtils.getInstance().openAlbum(ShopRzInputActivity.this);
                                        }
                                    });
                        }
                    }
                }).show();
                break;
            case R.id.iv_id_f:
                isLeftClicked = false;
                isShopSelected = false;
                AlertViewFactory.getInstance().getPhotoTypeAlertView(this, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            new RxPermissions(ShopRzInputActivity.this)
                                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) {
                                            CameraUtils.getInstance().takeCamera(ShopRzInputActivity.this);
                                        }
                                    });
                        } else if (position == 1) {
                            new RxPermissions(ShopRzInputActivity.this)
                                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                                    .subscribe(new Consumer<Boolean>() {
                                        @Override
                                        public void accept(Boolean aBoolean) {
                                            CameraUtils.getInstance().openAlbum(ShopRzInputActivity.this);
                                        }
                                    });
                        }
                    }
                }).show();
                break;
//            case R.id.iv_yy_zz:
//                isShopSelected = true;
//                AlertViewFactory.getInstance().getPhotoTypeAlertView(this, new OnItemClickListener() {
//                    @Override
//                    public void onItemClick(Object o, int position) {
//                        if (position == 0) {
//                            new RxPermissions(ShopRzInputActivity.this)
//                                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
//                                    .subscribe(new Consumer<Boolean>() {
//                                        @Override
//                                        public void accept(Boolean aBoolean) {
//                                            CameraUtils.getInstance().takeCamera(ShopRzInputActivity.this);
//                                        }
//                                    });
//                        } else if (position == 1) {
//                            new RxPermissions(ShopRzInputActivity.this)
//                                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
//                                    .subscribe(new Consumer<Boolean>() {
//                                        @Override
//                                        public void accept(Boolean aBoolean) {
//                                            CameraUtils.getInstance().openAlbum(ShopRzInputActivity.this);
//                                        }
//                                    });
//                        }
//                    }
//                }).show();
//                break;
            case R.id.btn_sure:
                uploadPic();//先上传图片
                break;
        }
    }
    List<String> pics=new ArrayList<>();

    private void uploadPic(){
        pics.clear();
        if ("".equals(etName.getText().toString())) {
            ToastUtils.showToast("请填写姓名!");
            return;
        }
        if ("".equals(etId.getText().toString())) {
            ToastUtils.showToast("请填写身份证号!");
            return;
        }
        if(etId.getText().toString().length()!=18){
            ToastUtils.showToast("身份证号码格式不正确!");
            return;
        }
        if ("".equals(etPhone.getText().toString())) {
            ToastUtils.showToast("请填写手机号!");
            return;
        }
        if(etPhone.getText().toString().length()!=11){
            ToastUtils.showToast("手机号格式不正确!");
            return;
        }
        if (city == null || province == null || county == null) {
            ToastUtils.showToast("请选择城市!");
            return;
        }
        if (levelid == null) {
            ToastUtils.showToast("请选择店铺类型!");
            return;
        }

        if (leftid == null) {
            ToastUtils.showToast("请上传身份证正面图!");
            return;
        }
        if (rightid == null) {
            ToastUtils.showToast("上传身份证反面图!");
            return;
        }
        ArrayList<String> s=mPhotosSnpl.getData();

        for (int i = 0; i < s.size(); i++) {
            //上传图片
            mApiHelper.commitPic(s.get(i), new Observer<BaseBean<UserInfoBean>>() {
                @Override
                public void onSubscribe(Disposable d) {
                }

                @Override
                public void onNext(BaseBean<UserInfoBean> baseBean) {
                    if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                        pics.add(baseBean.getData().getId());
                    } else {
                        ToastUtils.showToast(baseBean.getMs());
                    }

                    if(pics.size()==s.size()){
                        mHandler.sendEmptyMessage(0x16);
                    }
                }

                @Override
                public void onError(Throwable e) {
                    pics.add("");
                    if(pics.size()==s.size()){
                        mHandler.sendEmptyMessage(0x16);
                    }
                }

                @Override
                public void onComplete() {
                }
            });
        }
    }

    private void setPickerView() {
        pvOptions = new OptionsPickerBuilder(ShopRzInputActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                ShopCateResponse.DataBean dataBean = levelList.get(options1);
                levelid = "" + dataBean.getCateid();

                tvShopType.setText(dataBean.getName());
            }
        }).build();
        pvOptions.setPicker(strList);
        pvOptions.show();
    }

    /**
     * 城市三级联动
     */
    private void selectAddress() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                province = options1Items.get(options1).getPickerViewText();
                city = options2Items.get(options1).get(options2);
                county = options3Items.get(options1).get(options2).get(options3);

                tvAddress.setText(province + city + county);
                tvAddress.setTextColor(Color.parseColor("#333333"));
            }
        }).setDividerColor(Color.GRAY)
                //.setTextColorCenter(getResources().getColor(R.color.blue)) //设置选中项文字颜色
                .setContentTextSize(16)
                //.setTitleText("城市选择")
                .setOutSideCancelable(true)// default is true
                .build();
        //默认选择河南省
        pvOptions.setSelectOptions(15);
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = getJson(this, "province.json");//获取assets目录下的json文件数据
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

    public String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        //                        Toast.makeText(RealNameActivity.this,"开始解析数据",Toast.LENGTH_SHORT).show();
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 写子线程中的操作,解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;

                case MSG_LOAD_SUCCESS:
                    //                    Toast.makeText(RealNameActivity.this,"解析数据成功",Toast.LENGTH_SHORT).show();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    //                    Toast.makeText(RealNameActivity.this,"解析数据失败",Toast.LENGTH_SHORT).show();
                    break;

                case 0x16:
                    submit();
                    break;
            }
        }
    };

    /**
     * 获取等级
     */
    private void getLevels() {
        OkHttpUtils.post()
                .url(UrlHost.SHANG_SHOP_TYPE)
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    ShopCateResponse dlLevelBean = JsonUtils.parseByGson(response, ShopCateResponse.class);
                    if (dlLevelBean == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(dlLevelBean.getCode())) {
                        List<ShopCateResponse.DataBean> dataBeans = dlLevelBean.getData();
                        levelList.clear();
                        strList.clear();
                        levelList.addAll(dataBeans);
                        for (int i = 0; i < dataBeans.size(); i++) {
                            ShopCateResponse.DataBean da = dataBeans.get(i);
                            strList.add(da.getName());
                        }
                    } else {
                        ToastUtils.showToast(dlLevelBean.getMs());
                    }
                }
            }
        });
    }

    /**
     * 获取等级
     */
    private void submit() {
        List<String> s=new ArrayList<>();
        for (int i = 0; i <pics.size() ; i++) {
            if(!"".equals(pics.get(i))){
                s.add(pics.get(i));
            }
        }
        Log.e("tag","选中图片数："+pics);
        StringBuffer sb=new StringBuffer();
        for (int i = 0; i <s.size(); i++) {
            if(i==s.size()-1){
                sb.append(s.get(i));
            }else{
                sb.append(s.get(i)+",");
            }
        }
        Log.e("tag","选中图片数："+s.size());

        zzid=sb.toString();

        OkHttpUtils.post()
                .url(UrlHost.SHANG_SUBMIT)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("name", etShopName.getText().toString())
                .addParams("code",  yqm.getText().toString())
                .addParams("categoryid", levelid)
                .addParams("realname", etName.getText().toString())
                .addParams("ID_number", etId.getText().toString())
                .addParams("phone", etPhone.getText().toString())
                .addParams("detail", etAddressDetail.getText().toString())
                .addParams("ID_pic_1", leftid)
                .addParams("ID_pic_2", rightid)
                .addParams("qualification", zzid)
                .addParams("province", province)
                .addParams("city", city)
                .addParams("county", county)
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    DaiLiShenQingResponse daiLiShenQingResponse = JsonUtils.parseByGson(response, DaiLiShenQingResponse.class);
                    if (daiLiShenQingResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(daiLiShenQingResponse.getCode())) {
                        ToastUtils.showToast(daiLiShenQingResponse.getMs());
                        finish();
                    } else {
                        ToastUtils.showToast(daiLiShenQingResponse.getMs());
                    }
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == RC_CHOOSE_PHOTO) {
            mPhotosSnpl.addMoreData(data.getStringArrayListExtra("EXTRA_SELECTED_PHOTOS"));
            return;
        } else if (requestCode == RC_PHOTO_PREVIEW) {
            mPhotosSnpl.setData(data.getStringArrayListExtra("EXTRA_SELECTED_PHOTOS"));
            return;
        }
        CameraUtils.getInstance().onActivityResult(this, requestCode, resultCode, data, new CameraUtils.OnResultListener() {
            @Override
            public void takePhotoFinish(String path) {
//                CameraUtils.getInstance().setCropType(CameraUtils.CropType.Default).cropPicture(ShopRzInputActivity.this, path);
                if (isShopSelected) {
//                    Glide.with(ShopRzInputActivity.this).load(path).into(ivYyZz);
                } else {
                    if (isLeftClicked) {//正面图
                        leftImagePath = path;
                        Glide.with(ShopRzInputActivity.this).load(path).into(ivIdZ);
                    } else {//反面图
                        rightImagePath = path;
                        Glide.with(ShopRzInputActivity.this).load(path).into(ivIdF);
                    }
                }

                String p=ImageUtils.compress(ShopRzInputActivity.this,System.currentTimeMillis()+".png",new File(path));
                commitPic(p);//上传图片
            }

            @Override
            public void selectPictureFinish(String path) {
//                CameraUtils.getInstance().setCropType(CameraUtils.CropType.Default).cropPicture(ShopRzInputActivity.this, path);
                if (isShopSelected) {
//                    Glide.with(ShopRzInputActivity.this).load(path).into(ivYyZz);
                } else {
                    if (isLeftClicked) {//正面图
                        leftImagePath = path;
                        Glide.with(ShopRzInputActivity.this).load(path).into(ivIdZ);
                    } else {//反面图
                        rightImagePath = path;
                        Glide.with(ShopRzInputActivity.this).load(path).into(ivIdF);
                    }
                }
                String p=ImageUtils.compress(ShopRzInputActivity.this,System.currentTimeMillis()+".png",new File(path));
                commitPic(p);//上传图片
            }

            @Override
            public void cropPictureFinish(String path) {
            }
        });
    }

    /**
     * 上传图片
     */
    private void commitPic(String path) {
        mApiHelper.commitPic(path, new Observer<BaseBean<UserInfoBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<UserInfoBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    if (isShopSelected) {
                        zzid = baseBean.getData().getId();
                    } else {
                        if (isLeftClicked) {
                            leftid = baseBean.getData().getId();
                        } else {
                            rightid = baseBean.getData().getId();
                        }
                    }
                } else {
                    ToastUtils.showToast(baseBean.getMs());
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 九宫格控件
     * 点击添加加号按钮执行的方法
     *
     * @param sortableNinePhotoLayout
     * @param view
     * @param position
     * @param models
     */
    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        choicePhotoWrapper();
    }

    /**
     * 九宫格控件
     * 点击删除按钮执行的方法
     *
     * @param sortableNinePhotoLayout
     * @param view
     * @param position
     * @param model
     * @param models
     */
    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        mPhotosSnpl.removeItem(position);
    }

    /**
     * 九宫格控件
     * 点击图片进入预览界面
     *
     * @param sortableNinePhotoLayout
     * @param view
     * @param position
     * @param model
     * @param models
     */
    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        Intent photoPickerPreviewIntent = new BGAPhotoPickerPreviewActivity.IntentBuilder(this)
                .previewPhotos(models) // 当前预览的图片路径集合
                .selectedPhotos(models) // 当前已选中的图片路径集合
                .maxChooseCount(mPhotosSnpl.getMaxItemCount()) // 图片选择张数的最大值
                .currentPosition(position) // 当前预览图片的索引
                .isFromTakePhoto(false) // 是否是拍完照后跳转过来
                .build();
        startActivityForResult(photoPickerPreviewIntent, RC_PHOTO_PREVIEW);
    }

    /**
     * 九宫格控件
     * 拖拽排序发生变法执行的方法
     *
     * @param sortableNinePhotoLayout
     * @param fromPosition
     * @param toPosition
     * @param models
     */
    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {
        //排序发生变化
    }

    /**
     * 九宫格控件
     * 添加图片，申请权限
     */
    private void choicePhotoWrapper() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
        File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "BGAPhotoPickerTakePhoto");

        Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(this)
                .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
                .maxChooseCount(mPhotosSnpl.getMaxItemCount() - mPhotosSnpl.getItemCount()) // 图片选择张数的最大值
                .selectedPhotos(null) // 当前已选中的图片路径集合
                .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
                .build();
        startActivityForResult(photoPickerIntent, RC_CHOOSE_PHOTO);
    }

    /**
     * 获取邀请码
     */
    private void getCode() {
        OkHttpUtils.post()
                .url(UrlHost.PCODE)
                .addParams("uid", SharePrefUtils.getUserId())
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    GetCodeResponse collectShopResponse = JsonUtils.parseByGson(response, GetCodeResponse.class);
                    if (collectShopResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(collectShopResponse.getCode())) {
                        String code=collectShopResponse.getData();
                        yqm.setText(code);
                    } else {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    }
                } else {
                }
            }
        });
    }
}
